package com.lw.common.web.configrue;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

public class MyShiroSessionDAO extends AbstractSessionDAO {
	
//	private StringRedisTemplate redismplate;
	@Autowired
	private RedisTemplate<String, Session> redisTemplate;

	public void update(Session session) throws UnknownSessionException {

		redisTemplate.opsForValue().set(session.getId().toString(), session, 1800, TimeUnit.SECONDS);
	}

	public void delete(Session session) {
		redisTemplate.delete(session.getId().toString());
	}

	public Collection<Session> getActiveSessions() {
		/**
		 * @todo
		 */
		return new ArrayList<Session>();
	}

	@Override
	protected Serializable doCreate(Session session) {

		Serializable sid = this.generateSessionId(session);
		assignSessionId(session, sid);
		System.err.println(session);
		System.err.println(session.toString());
		redisTemplate.opsForValue().set(sid.toString(), session, 1800, TimeUnit.SECONDS);
		return sid;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		Session session = redisTemplate.opsForValue().get(sessionId.toString());
		// 计算过期时间，是从最后一次使用开始
		redisTemplate.opsForValue().set(sessionId.toString(), session, 1800, TimeUnit.SECONDS);
		return session;
	}
}
